<template>
  <div class="pad-l-20 pad-r-20">
    <el-tabs class="circle-tab" v-model="activeName">
      <el-tab-pane label="编辑内容基础信息" name="1" :disabled="tabDisabled">
        <div>
          <el-form :model="contentArticle" label-width="130px" :rules="rules" ref="contentArticle" class="pad-t-15">
            <el-form-item label="基本信息" class="one-label">
              <el-form-item label="排序：" label-width="140px">
                <el-input v-model="contentArticle.sortNo" class="long-input" type="number"/>
                <div class="tips">数字越大，排序越靠前，如果为空，默认排序方式为创建时间</div>
              </el-form-item>
              <el-form-item label="内容标题：" label-width="140px" prop="title">
                <div class="flex">
                  <el-input v-model="contentArticle.title" class="long-input" placeholder="请输入内容名称，例如：文章名称、活动名称等等"/>
                </div>
              </el-form-item>
              <el-form-item label="作者：" label-width="140px" prop="authorName">
                <div class="flex">
                  <el-input v-model="contentArticle.authorName" class="long-input" placeholder="请输入作者名称"/>
                </div>
              </el-form-item>
              <el-form-item label="封面图：" prop="mainPicUrl" label-width="140px">
                <div class="flex">
                  <div class="flex v-align-c">
                    <el-upload action="/api/common/uploadFiles"
                    accept="image/jpeg,image/gif,image/png,image/bmp"
                    list-type="picture-card-auto"
                    :before-upload="beforeUpload" name="files"
                    :data="token" :show-file-list="false"
                    v-loading="fileLoading"
                    :on-success="handleUploadSuccess">
                      <img v-if="contentArticle.mainPicUrl" :src="contentArticle.mainPicUrl" width="148px" height="148px">
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                  </div>
                </div>
                <div class="tips mar-t-3">建议尺寸：750*750像素，最多上传1张</div>
              </el-form-item>
            </el-form-item>
          </el-form>
          <component-details v-if="detailsBoolean" ref="componentDetail" :templateId="templateId" :contentInfo="contentArticle" formFlag="0"></component-details>
        </div>
      </el-tab-pane>      
    </el-tabs>
    <template>
      <div class="bottom-btn pad-b-15">
        <el-button type="primary" class="pad-l-30 pad-r-30" @click="submit(1)" :disabled="disabledButton">保存</el-button>
        <el-button type="success" class="pad-l-30 pad-r-30" @click="submit(2)" :disabled="disabledButton">保存并分发</el-button>
        <el-button class="pad-l-30 pad-r-30" @click="submit(3)" :disabled="disabledButton">预览效果</el-button>
      </div>
    </template>

    <el-dialog title="" :visible.sync="financeVisible" :close-on-press-escape="true" class="payment-box align-c" width="320px">
      <img :src="contentArticleCode" style="width: 300px;height: 300px">
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.bottom-btn{
  margin-top: -10px;
  text-align: center;
  background: #f8f8f8;
  padding-top: 27px;
  padding-bottom: 27px;
}
@media screen and (max-width: 1220px) {
  .bottom-btn{
    left: 156px;
  }
}
@media screen and (max-width: 1045px) {
  .bottom-btn{
    left: 398px;
  }
}
.span-bar{
  padding: 0 50px;
 }
 .remove-btn{
   padding: 7px 6px!important;
 }
 .long-input{
  width: 80%;
 }
 .long-input-2{
  width: 55%;
  margin-right: 5%;
 }
 .long-input-3{
  width: 55%;
 }
 .short-input{
  width: 20%;
 }
 .short-input-2{
  width: 25%;
 }
 .default-input{
  width: 50%;
 }
 .tips{
  color: gray;
  font-size: 12px;
  line-height: 1.2;
  padding-top: 5px;
 }
 .picture{
  width: 130px;
  height: 130px;
  display: block;
 }
 .pic-bar{
  position: relative;
  .close-icon{
    position: absolute;
    right: -30px;
    top: -11px;
    width: 31px;
    height: 40px;
    padding: 0 7px;
    cursor: pointer;
  }
  span{
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100%;
    display: block;
    color: #fff;
    text-align: center;
    padding: 3px 0;
    background: rgba(0,0,0,0.5);
    cursor: pointer;
  }
 }
 .pic-add{
  background: #fff;
  border: #d3d3d3 1px dashed;
  border-radius: 5px;
  padding: 0 45px;
 }
</style>

<script>
  import ComponentDetails from '@/components/ComponentTemplate/ComponentDetails'
  import { getNameByPath } from '@/utils/get-name-by-path' // 不要删除，根据URL获取文件名
  import { getStrByLength } from '@/utils'
  import { getToken } from '@/utils/auth'
  import { getContentArticle, saveContentArticle, getContentArticleCode } from '@/api/content/distributeArticle'

  export default {
    name: getNameByPath(),
    components: {
      ComponentDetails
    },
    data() {
      return {
        activeName: '1',
        submitType: 1,
        contentArticleCode: '',
        articleId: '',
        templateId: '',
        disabledButton: false,
        tabDisabled: true,
        financeVisible: false,
        listDetails: [],
        contentArticle: {
          sortNo: 0,
          articleId: '',
          enterpriseId: this.getEnterpriseId(),
          title: '',
          authorName: '',
          templateId: '',
          mainPicUrl: '',
          listDetails: []
        },
        rules: {
          title: [
            { required: true, message: '请填写文章标题', trigger: 'blur' }
          ]
        },
        picData: {},
        picBoolean: false,
        categoryData: [],
        fileLoading: false,
        detailsBoolean: false
      }
    },
    mounted() {
      const that = this
      // 文本表单值设置
      this.$bus.$on('ComponentTemplate.templateId.content', function(data) {
        that.templateId = ''
        that.templateId = data
        that.saveTemplate()
        that.$bus.$off('ComponentTemplate.templateId.content')
      })
      this.$bus.$on('disabledButtonEmit', function(data) {
        that.disabledButton = false
      })
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    // 初始化页面
    created() {
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.articleId) {
        this.articleId = queryParams.articleId
      } else {
        this.detailsBoolean = true
      }
      // 可处理传图成功后，图片展示
      if (Object.keys(this.picData).length === 0) {
        this.picBoolean = false
      } else {
        this.picBoolean = true
      }
      this.token = { accessToken: getToken() }
      const that = this
      this.$bus.$on('backStep', function(data) {
        that.activeName = data
      })
      this.initContentArticle()
    },
    methods: {
      initContentArticle() {
        if (this.articleId) {
          getContentArticle(this.articleId).then(response => {
            if (response.isError) return
            this.contentArticle = response.data
            this.templateId = response.data.templateId
            this.detailsBoolean = true
          })
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      // 表单提交
      submit(item) {
        this.disabledButton = true
        // 排序校验
        const reg = /^[+]{0,1}(\d+)$/
        if (!reg.test(this.contentArticle.sortNo)) {
          this.$message.error('排序必须大于等于0的正整数')
          this.disabledButton = false
          return
        }
        if (this.contentArticle.authorName.length > 8) {
          this.$message.error('作者名字小于等于8个字')
          this.disabledButton = false
          return
        }
        if (this.contentArticle.title.length > 255) {
          this.$message.error('文章标题小于等于255个字')
          this.disabledButton = false
          return
        }
        if (!this.contentArticle.title) {
          this.$message.error('文章标题不能为空')
          this.disabledButton = false
          return
        }
        this.submitType = item
        if (item === 3) {
          this.saveTemplate()
          return
        }
        const that = this
        that.$refs.componentDetail.submit(0)
      },
      saveTemplate(data) {
        if (this.templateId) {
          this.contentArticle.templateId = this.templateId
          saveContentArticle(this.contentArticle).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: response.msg
            })
            if (this.submitType === 1) {
              this.$router.push({ path: '/content/distributeArticle/index' })
            }
            if (this.submitType === 2) {
              this.$router.push({ path: '/content/distributeArticle/release/index', query: { articleId: response.data }})
            }
            if (this.submitType === 3) {
              // 生成二维码
              getContentArticleCode(response.data).then(response => {
                if (response.isError) return
                this.contentArticleCode = response.data
                this.financeVisible = true
              })
            }
            this.disabledButton = false
          })
        }
      },
      handlePictureCardPreview(file) {
        console.log(file)
        // 上传成功后处理
        this.picBoolean = true
        this.picData = {
          id: 1,
          src: 'http://bpic.588ku.com/back_origin_min_pic/19/04/17/34cfe97268d276ac28bcfbebfaffaad9.jpg'
        }
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.fileLoading = true
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        this.fileLoading = false
        if (res.code === 101) {
          this.contentArticle.mainPicUrl = res.data[0]
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      getStrByLength(str, n) {
        return getStrByLength(str, n)
      }
    }
  }
</script>
